package com.example.jikejavatrain.concurrent;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;

/**
 * @author fangzhuangzhan
 * @date 2021/08/28 11:14
 */
public class StartThreadTest {

    public final static Map data = new HashMap();

    public static void main(String[] args) throws ExecutionException, InterruptedException, Exception {
        final ExecutorService executorService = Executors.newCachedThreadPool();

        // 第一种拿到新线程返回值的方法
        final Future<Map> result =executorService.submit(new Callable<Map>() {
            @Override
            public Map call() throws Exception {
                System.out.println("睡眠2s，让main线程等待。。。。");
                Thread.sleep(2000);
                final HashMap hashMap = new HashMap();
                hashMap.put("name","fzz");
                hashMap.put("age","21");
                return hashMap;
            }
        });
        final Map map = result.get();
        System.out.println(map);



        // 第二种拿到新线程返回值的方法
        Thread a = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("睡眠2s，让main线程等待。。。。");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                data.put("name","fzz");
            }
        });
        //executorService.execute(a);
        a.start();
        a.join();
        System.out.println(data);


        // 第三种拿到新线程返回值的方法
        CompletableFuture re = CompletableFuture.supplyAsync(() ->{
            System.out.println("睡眠2s，让main线程等待。。。。");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "ss";
        },executorService);
        System.out.println(re.get());


        executorService.shutdown();
    }
}
